﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoShutDown
{
    class ShutImplement
    {
        public static readonly string DefaultShutDownTime = "22:00:00";
        public DateTime NextShutDownTime { get; private set; }


        private System.Timers.Timer _timer;
        public ShutImplement()
        {
            _timer = new System.Timers.Timer(60000);
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
            _timer.Enabled = false;
        }

        public void Start()
        {

            Stop();

            System.Configuration.AppSettingsReader reder = new System.Configuration.AppSettingsReader();
            string downTime = string.Format("{0}", reder.GetValue("DownTime", typeof(string)));
            NextShutDownTime = GetShutDownTime(downTime);

            //_url= 
            _timer.Enabled = true;
            _timer.Start();
        }

        public DateTime GetShutDownTime(string downTime)
        {
            if (string.IsNullOrEmpty(downTime))
            {
                downTime = DefaultShutDownTime;
            }

            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"(([0-1][0-9])|([2][0-3])):[0-5][0-9]:[0-5][0-9]");
            if (!reg.Match(downTime).Success)
            {
                downTime = DefaultShutDownTime;
            }

            var str = string.Format("{0:yyyy-MM-dd} {1}", DateTime.Now, downTime);
            var nextTime = DateTime.Parse(str);
            if (nextTime < DateTime.Now)
            {
                nextTime = nextTime.AddDays(1);
            }

            return nextTime;
        }

        public void Stop()
        {
            _timer.Stop();
            _timer.Enabled = false;
        }

        public bool IsRuning
        {
            get
            {
                return _timer.Enabled;
            }
        }

        void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _timer.Stop();

            if (NextShutDownTime < DateTime.Now)
            {
                NextShutDownTime = NextShutDownTime.AddDays(1);
                shutDown();
            }
            else
            {
                _timer.Start();
            }
        }

        private void shutDown()
        {
            System.Diagnostics.Process.Start("shutdown", "/s /t 0 /f");
        }

    }

}
